package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.JenisCustomerEntity;
import com.kifas.model.xml.JenisCustomerModel;
import com.kifas.model.xml.PersistStatus;
import com.kifas.service.EntityServiceManager;

@Component
@Scope("prototype")
@Path("/JenisCustomers")
public class JenisCustomerController {

	private static Logger log = Logger.getLogger(JenisCustomerController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;

	@GET
	@Produces(MediaType.TEXT_XML)
	public List<JenisCustomerModel> getJenisCustomers() {
		List<JenisCustomerEntity> jenisCustomers = entityManager.getJenisCustomers();
		return transformList(jenisCustomers);
	}

	@POST
	@Produces(MediaType.APPLICATION_XML)
	@Consumes(MediaType.APPLICATION_XML)
	public PersistStatus insert(JAXBElement<JenisCustomerModel> xml) {
		JenisCustomerModel model = xml.getValue();
		JenisCustomerEntity jenisCustomer = new JenisCustomerEntity(null, model.getJenisCustomer());
		try {
			entityManager.persist(jenisCustomer);
		} catch (Exception e) {
			log.error("can not persist jenis customer entity", e);
			return new PersistStatus("JenisCustomerEntity", "failed", "can not persist jenis customer entity");
		}
		return new PersistStatus("JenisCustomerEntity", "success");
	}

	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus update(JAXBElement<JenisCustomerModel> xml) {
		JenisCustomerModel model = xml.getValue();
		JenisCustomerEntity jenisCustomer = new JenisCustomerEntity(model.getIdJenisCustomer(), model.getJenisCustomer());
		try {
			entityManager.update(jenisCustomer);
		} catch (Exception e) {
			log.error("can not update jenis customer entity", e);
			return new PersistStatus("JenisCustomerEntity", "failed", "can not update jenis customer entity");
		}
		return new PersistStatus("JenisCustomerEntity", "success");
	}

	private JenisCustomerModel transform(JenisCustomerEntity jenisCustomer) {
		return new JenisCustomerModel(jenisCustomer.getIdJenisCustomer(), jenisCustomer.getJenisCustomer(), jenisCustomer.getCreatedBy());
	}

	private List<JenisCustomerModel> transformList(List<JenisCustomerEntity> jenisCustomers) {
		List<JenisCustomerModel> jenisCustomerEntities = new ArrayList<JenisCustomerModel>();
		for (JenisCustomerEntity jenisCustomer : jenisCustomers) {
			jenisCustomerEntities.add(transform(jenisCustomer));
		}
		return jenisCustomerEntities;

	}
}
